<template>
  <div class="setting-container">
    <div class="app-container">
      <!-- 卡片组件 -->
      <el-card class="box-card">
        <!-- 使用 Tabs 组件完成标签页布局 -->
        <el-tabs v-model="activeName" @tab-click="tabClickFn">
          <el-tab-pane label="角色管理" name="first" class="tab-pane">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="addRoleBtnFn"
              >新增角色</el-button>
            </el-row>
            <!-- 使用 Table 组件实现用户角色的渲染 -->
            <el-table border style="width: 100%" :data="rolesList">
              <el-table-column type="index" label="序号" width="120" />
              <el-table-column label="角色名" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="setRoles(scope.row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRoles(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRoles(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination
              :current-page="query.page"
              :page-sizes="[10, 15, 20, 25]"
              :page-size="query.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="second" class="tab-pane">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form :model="formData" label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        :title="flag?'编辑角色' : '新增角色'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
        @close="cancelRoles"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="roleRules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>

        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="cancelRoles">取消</el-button>
            <el-button size="small" type="primary" @click="roleSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限弹框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="dialogVisible"
        width="50%"
        @close="$refs.permission.$refs.tree.setCheckedKeys([])"
      >
        <assign-permission ref="permission" :dialog-visible.sync="dialogVisible" :permission-list="permissionList" :role-ids-list="roleIdsList" @updateList="updateList" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRolesAPI, getCompanyInfoAPI, addRoleAPI, updateRoleAPI, deleteRoleAPI, getPermissionListAPI, getRoleIdAPI, assignPermAPI } from '@/api/index.js'
import { mapGetters } from 'vuex'
import { transTree } from '@/utils'
import AssignPermission from '@/views/setting/components/assignPermission.vue'
export default {
  components: {
    AssignPermission
  },
  data() {
    return {
      activeName: 'first', // 关联tab栏选中的name值
      query: { // 查询参数
        page: 1, // 当前页面(页码)
        pagesize: 10 // 页面显示的条数
      },
      rolesList: [], // 角色列表(表格展示数据)
      total: 0, // 角色数据总条数,
      formData: {}, // 公司信息对象
      showDialog: false, // 控制弹框的隐藏和展示
      // 添加角色
      roleForm: {
        name: '',
        description: ''
      },
      flag: false,
      dialogVisible: false,
      roleId: '',
      permissionList: [],
      roleIdsList: [], // 某个角色的权限点数组
      // 添加角色验证
      roleRules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }

    }
  },
  computed: {
    ...mapGetters(['companyId'])
  },
  created() {
    this.getRolesList()
    this.getPermissionListFn()
  },
  methods: {
    tabClickFn() {
      if (this.activeName === 'second') {
        this.getCompanyInfo()
      }
    },
    // 获取初始铺设页面数据
    async getRolesList() {
      const { data: { rows, total }} = await getRolesAPI(this.query)
      this.total = total
      this.rolesList = rows
    },
    // 获取公司信息
    async getCompanyInfo() {
      const { data } = await getCompanyInfoAPI(this.companyId)
      this.formData = data
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(size) {
      this.query.pagesize = size
      this.query.page = 1
      this.getRolesList()
    },

    // 当前页码发生改变时触发
    handleCurrentChange(page) {
      this.query.page = page
      this.getRolesList()
    },

    // 设置角色
    async setRoles(id) {
      this.roleId = id
      // console.log(id)
      const { data: { permIds }} = await getRoleIdAPI(id)
      this.roleIdsList = permIds
      this.dialogVisible = true
    },

    // 编辑角色
    editRoles(obj) {
      this.showDialog = true
      this.flag = true
      // 轻易不要改变el-form绑定的表单数据对象,会导致reset重置失效
      this.roleForm = obj
      // console.log(obj)
    },

    // 删除角色
    async delRoles(obj) {
      try {
        await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', { type: 'warning' })
        const { message, success } = await deleteRoleAPI(obj.id)
        if (!success) return this.$message.error(message)
        this.$message.success(message)
        if (this.rolesList.length === 1 && this.query.page > 1) this.query.page--
        this.getRolesList()
      } catch (e) {
        this.$message.info('取消删除')
      }
    },
    // 弹框添加权限按钮
    roleSubmit() {
      this.$refs.roleForm.validate(async valid => {
        if (!valid) return
        if (this.flag) {
          const { message, success } = await updateRoleAPI(this.roleForm)
          if (!success) this.$message.error(message)
          else this.$message.success(message)
        } else {
          const { message, success } = await addRoleAPI(this.roleForm)
          if (!success) this.$message.error(message)
          else this.$message.success(message)
        }
        this.showDialog = false
        this.getRolesList()
        this.$refs.roleForm.resetFields()
        this.roleForm = {
          name: '',
          description: ''
        }
      })
    },

    // 弹框取消权限按钮
    cancelRoles() {
      this.roleForm = {
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 新增角色按钮点击事件
    addRoleBtnFn() {
      this.flag = false
      this.showDialog = true
    },
    // 获得角色列表
    async getPermissionListFn() {
      const { data } = await getPermissionListAPI()
      this.permissionList = transTree(data, '0')
    },
    // 更新权限
    async updateList(list) {
      const obj = {
        id: this.roleId,
        permIds: list
      }
      console.log(obj)
      const res = await assignPermAPI(obj)
      console.log(res)
    }
  }

}
</script>

<style lang="scss" scoped>
.box-card {
  padding: 10px 30px;
}

.tab-pane {
  padding: 20px;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}
</style>

